案例需求:
当我们安装好集群后,如果想要把 kubectl 命令交给用户使用,就不得不对用户的身份进行认证和对其权限做出限制。
创建一个测试用户testmonitor只能在其自己的命名空间testmonitor中拥有所有权限。
生成证书密钥
本案例没有生成新的CA证书,用的kubernetes自带的CA证书,如有需求,也可以自己生成,此处不做赘述。(或者获取到master节点上的ca.key放到本地执行也可以)
在kubernetes集群master节点上创建一个RBAC_testmonitor目录,目录可以自定义。用cd命令进入到该目录下,用OpenSSL创建密钥证书。1
2
3
4# 创建一个一次性签10年的证书
openssl genrsa -out testmonitor.key 2048
openssl req -new -key testmonitor.key -out testmonitor.csr -subj "/CN=testmonitor/O=develops"
openssl x509 -req -in testmonitor.csr -CA /etc/kubernetes/pki/ca.crt -CAkey=/etc/kubernetes/pki/ca.key -CAcreateserial -out testmonitor.crt -days 3650
生成config文件
1 | # 设置集群参数 |
以上执行一个步骤就可以看一下 testmonitor.kubeconfig 的变化。里面最主要的三个东西
- cluster: 集群信息,包含集群地址与公钥
- user: 用户信息,客户端证书与私钥,真正的信息是从证书里读取出来的,人能看到的只是给人看的。
- context: 维护一个三元组,namespace cluster 与 user
RoleBinding
如果我们想限制 testmonitor 用户的行为,需要使用 RBAC创建角色绑定以将该用户的行为限制在某个或某几个 namespace 空间范围内。
下面 role-testmonitor.yaml 文件内容实现了创建角色,绑定用户1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26apiVersion: rbac.authorization.k8s.io/v1
kind: "Role"
metadata:
name: testmonitorr
namespace: testmonitor
rules:
- apiGroups: [""]
resources: ["*"]
verbs: ["*"]
- apiGroups: ["apps","extensions","namespace"]
resources: ["*"]
verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: "RoleBinding"
metadata:
name: testmonitorrb
namespace: testmonitor
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: "Role"
name: testmonitorr # 角色信息
subjects:
- kind: User
name: testmonitor # 目标用户
namespace: testmonitor
1 | kubectl create -f role-testmonitor.yaml |
已存在用户新增命名空间权限
1 | kubectl create rolebinding dev --clusterrole=testmonitorr --user=testmonitor --namespace=dev-test |
效果实现
使用生成的config文件测试访问
已经不能访问default空间的内容1
2[TestMonitor] kubectl get pod -n default
Error from server (Forbidden): pods is forbidden: User "testmonitor" cannot list resource "pods" in API group "" in the namespace "default"
查看config中的环境1
2
3[TestMonitor] kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* testmonitor-context devk8s testmonitor testmonitor
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/11/30/Kubernetes 创建用户认证授权的kubeconfig文件/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!